package pojo;

public class SinglyLinkedList<T> implements LinearList<T> {
    public Node<T> head;
    public SinglyLinkedList(){
        head = new Node<T>();
    }
    @Override
    public T get(int i){
        int j = 0;
        Node<T> p = this.head.next;
        for (;p!=null && j<i;j++){
            p = p.next;
        }
        return (j>=0 && p!=null) ? p.data : null;
    }

    @Override
    public void set(int i, T t) {
        int j = 0;
        Node<T> p = this.head.next;
        for (;p!=null && j<i;j++){
            p = p.next;
        }
        if (p!=null){
            p.data = t;
        }
    }

    @Override
    public int insert(T t) {
        return this.insert(this.size(), t);
    }

    @Override
    public int insert(int i, T t) {
        int j = 0;
        if (t==null){
            throw new RuntimeException("插入元素为空");
        }
        Node<T> p = this.head;
        while (p!=null && j<i){
            p = p.next;
            j++;
        }
        if (j==i){
            Node<T> s = new Node<>(t, p.next);
            p.next = s;
            return i;
        }else{
            return -1;
        }
    }

    @Override
    public T remove(int i) {
        int j = 0;
        Node<T> p = this.head;
        while (p!=null && j<i){
            p = p.next;
            j++;
        }
        if(p.next!=null && j==i){
            T old = p.next.data;
            p.next = p.next.next;
            return old;
        }else{
            return null;
        }
    }

    @Override
    public boolean contains(T key) {
        Node<T> p = this.head.next;
        while (p!=null){
            if (p.data.equals(key)){
                return true;
            }
            p = p.next;
        }
        return false;
    }

    @Override
    public int indexOf(T key) {
        int i = 0;
        Node<T> p = this.head.next;
        while (p!=null){
            if (p.data.equals(key)){
                return i;
            }
            i++;
            p = p.next;
        }
        return -1;
    }

    @Override
    public int size() {
        int n = 0;
        Node<T> p = this.head.next;
        while (p!=null){
            n++;
            p = p.next;
        }
        return n;
    }

    @Override
    public void clear() {
        this.head.next = null;
    }

    @Override
    public boolean isEmpty() {
        return this.head.next == null;
    }

    @Override
    public void printList() {
        Node<T> p = this.head.next;
        while (p!=null){
            System.out.print(p.data + " ");
            p = p.next;
        }
    }
}
